<?php

namespace Agent\Controller;

use Utuo\BackgroundController;
use Utuo\Phpass;

class LoginController extends BackgroundController {
	// 登录地址
	public function indexAction() {
		layout(false);
		$this->display();
	}
	
	// 登录提交
	public function loginAction() {
		$email = I('email', '', 'htmlspecialchars');
		$password = I('password', null, false);
		$verify = I('verify');
		
		// 验证码
		if (!check_verify($verify, 1)) {
			$data['error'] = 1;
			$data['message'] = '验证码不正确';
			$this->ajaxReturn($data);
		}
		
		$admin = M('AgentAdmin a')->join("__AGENT__ b on a.agent_id=b.id")->where("(a.user_name='%s' or a.email='%s') and a.is_deleted=0", $email, $email)->field("a.*,b.login_count as p_login_count,b.cid")->find();
		if (empty($admin)) {
			$data['error'] = 1;
			$data['message'] = '登录账号不存在';
		} else {
			if (Phpass::check($password, $admin['password'])) {
				if ($admin['status'] == 0) {
					$data['error'] = 1;
					$data['message'] = '禁止登录';
				} else {
					$data['error'] = 0;
					$data['message'] = '登录成功';
					$this->setLogin($admin[C("AUTH_FIELD")], $admin['name'], array(C("USER_AUTH_KEY")=>$admin['id'] ? $admin['id'] : 0, 'cid' => $admin['cid'] ));
					M('Agent')->where("id=".$admin['agent_id'])->save(array(
							'last_login_time' => time(),
							'last_login_ip' => get_client_ip(),
							'login_count' => $admin['p_login_count'] + 1
					));
					M('AgentAdmin')->where("id=".$admin['id'])->save(array(
							'last_login_time' => time(),
							'last_login_ip' => get_client_ip(),
							'login_count' => $admin['login_count'] + 1
					));
				}
			} else {
				$data['error'] = 1;
				$data['message'] = '登录密码不正确';
			}
		}
		$this->ajaxReturn($data);
	}
	
	// 退出登录
	public function logoutAction() {
		$this->setLogout();
		$this->redirect('Agent/Login/index', null, 1, '已经退出，转到登录页面……');
	}
	
	// 验证码
	public function verifyAction() {
		parent::createVerify(1);
	}
}